package com.zpark.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zpark.dto.AppointmentQueryDTO;
import com.zpark.dto.AppointmentUpdateDTO;
import com.zpark.entity.patients.PatientAppointments;
import com.zpark.service.PatientAppointmentsService;
import com.zpark.status.StatusCode;
import com.zpark.utils.ResultUtils;
import com.zpark.utils.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/appointments")
public class AppointmentsController {
    @RequestMapping("/test")
    public ResultVO test() {
        return ResultUtils.success("成功");
    }

    @Resource
    private PatientAppointmentsService patientAppointmentsService;

    // 获取整个表预约数据
    @RequestMapping("/getAllAppointments")
    public ResultVO getAllAppointments(
        @RequestParam(required = false) String status,
        @RequestParam(required = false) String consultationType,
        @RequestParam(required = false) String timeRange,
        @RequestParam(required = false) String searchQuery,
        @RequestParam(defaultValue = "1") int pageNum,  // 添加pageNum参数，默认值为1
        @RequestParam(defaultValue = "10") int pageSize) { // 添加pageSize参数，默认值为10

        // 构建查询DTO
        AppointmentQueryDTO queryDTO = new AppointmentQueryDTO();
        queryDTO.setStatus(status);
        queryDTO.setConsultationType(consultationType); // 直接设置为字符串
        queryDTO.setSearchQuery(searchQuery);

        // 处理时间范围
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();

        if ("today".equals(timeRange)) {
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            Date todayStart = calendar.getTime();

            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            Date todayEnd = calendar.getTime();

            queryDTO.setStartDate(todayStart);
            queryDTO.setEndDate(todayEnd);
        } else if ("upcoming".equals(timeRange)) {
            queryDTO.setStartDate(now);
        } else if ("past".equals(timeRange)) {
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            queryDTO.setEndDate(calendar.getTime());
        }

        Page<PatientAppointments> page = new Page<>(pageNum, pageSize);
        IPage<PatientAppointments> appointmentsPage = patientAppointmentsService.listAppointmentsByPage(page, queryDTO);

        List<PatientAppointments> appointments = patientAppointmentsService.getAllAppointments();
        return ResultUtils.success("查询成功", appointments);
        }

    // 删除预约记录
    @RequestMapping("/deleteAppointment")
    public ResultVO deleteAppointment(String appointmentId) {
        try {
            PatientAppointments deletedAppointment = patientAppointmentsService.deleteAppointment(appointmentId);
            if (deletedAppointment != null) {
                return ResultUtils.success("删除成功", deletedAppointment);
            } else {
                return ResultUtils.error(StatusCode.valueOf("删除失败"));
            }
        } catch (Exception e) {
            return ResultUtils.error(StatusCode.valueOf(e.getMessage()));
        }
    }

    // 修改预约表数据
    @PutMapping("/updateAppointment")
    public ResponseEntity<ResultVO> updateAppointment(
        @RequestBody @Valid AppointmentUpdateDTO dto) {

        // 1. 查询现有预约
        PatientAppointments existing = patientAppointmentsService.getAppointmentByAppointmentId(dto.getAppointmentId());
        if (existing == null) {
            return ResponseEntity.badRequest()
                .body(ResultVO.error(404, "预约记录不存在"));
        }

        // 2. 更新可修改字段到新对象
        PatientAppointments updateData = new PatientAppointments();
        BeanUtils.copyProperties(existing, updateData);
        updateData.setAppointmentDate(dto.getAppointmentDate());
        updateData.setTimeSlot(dto.getTimeSlot());
        updateData.setSymptoms(dto.getSymptoms());
        // 3. 调用服务保存新记录
        PatientAppointments updated = patientAppointmentsService.updateAppointment(updateData);


        // 4. 返回成功响应
        return ResponseEntity.ok(ResultVO.success("预约修改成功", updated));
    }

    // 根据预约编号查询
    @RequestMapping("/getPatientAppointmentsById")
    public ResultVO getPatientAppointmentsById(String appointmentId) {
        PatientAppointments patientAppointments = patientAppointmentsService
            .getAppointmentByAppointmentId(appointmentId);
        return ResultUtils.success("查询成功",patientAppointments);
    }

    // 新增查询接口
    @PostMapping("/query")
    public ResultVO queryAppointments(@RequestBody AppointmentQueryDTO queryDTO) {
        List<PatientAppointments> appointments = patientAppointmentsService.queryAppointments(queryDTO);
        return ResultUtils.success("查询成功", appointments);
    }

    // 在 AppointmentsController.java 中添加
    @PutMapping("/cancel/{appointmentId}")
    public ResultVO cancelAppointment(@PathVariable String appointmentId) {
        try {
            boolean success = patientAppointmentsService.cancelAppointment(appointmentId, "患者主动取消");
            if (success) {
                return ResultUtils.success("取消预约成功");
            } else {
                return ResultUtils.error(StatusCode.valueOf("取消预约失败"));
            }
        } catch (Exception e) {
            return ResultUtils.error(StatusCode.valueOf(e.getMessage()));
        }
    }

}
